package bidsanity

import grails.converters.JSON

class ListingService {
    def jmsService

    def createListing(Map params) { return createListing(params?.name, params?.endDate,
                                                         params?.startingBidPrice, params?.description,
                                                         params?.sellerId, params?.winnerId)}
    def createListing(name, endDate, startingBidPrice, description, sellerId, winnerId) {
        def seller = (sellerId != null ? Customer.get(sellerId) : null)
        def winner = (winnerId != null ? Customer.get(winnerId) : null)
        def l = new Listing(
                name: name,
                endDate: endDate,
                startingBidPrice: startingBidPrice,
                description: description,
                seller: seller,
                winner: winner)
        l.save(flush: true)
        scheduleListingEnd(l)
        return l
    }

    def scheduleListingEnd(Listing listing){
        
        if(listing.endDate > new Date()){
            Timer t = new Timer(true)
            t.schedule(new ListingEndTask(listingId: listing.id, jmsService: jmsService), listing.endDate)
        }
        
    }

}



class ListingEndTask extends TimerTask {
    def listingId
    def jmsService

    public void run() {
        
        Listing listing = Listing.get(listingId)
        if(listing) {
            def winningBid
            if(listing.bids.size() > 0){
                winningBid = listing.bids.sort{it.amount*-1}[0]
            }
            def details = [:]
            details.listingDescription = listing.description
            details.sellerEmail = listing.seller.emailAddress
            details.listingId = listing.id
            if(winningBid){
                details.winnerEmail = winningBid.bidder.emailAddress
                details.winningAmount = winningBid.amount
                sendJMSMessage('listing.complete', (details as JSON).toString());
            }
            else{
                sendJMSMessage('listing.nobids', (details as JSON).toString());
            }
        }
    }

    public void sendJMSMessage(String queueName, String message){
        jmsService.send(queue: queueName, message);
    }

}